package com.elong.android.specialhouse.base;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.IConfig;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.activity.MessageListActivity;
import com.elong.android.specialhouse.activity.YouFangLoginManager;
import com.elong.android.specialhouse.push.PushReceiver;
import com.elong.android.specialhouse.ui.CustomDialogBuilder.Observer;
import com.elong.android.specialhouse.utils.ElongValidator;
import com.elong.android.specialhouse.utils.JSONHelper;
import com.elong.android.specialhouse.utils.PrefUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.myelong.activity.LoginActivity;
import com.elong.myelong.usermanager.User;

// import com.umeng.analytics.MobclickAgent;
public abstract class PluginBaseActivity extends Activity implements View.OnClickListener, Observer {

    public final static String TAG = "PluginBaseActivity";
    private static final int DEFAULT_RECEIVER_PRIORITY_NO_RECEIVER = -1 ;
    private static final int REQUEST_CODE_LOGIN = 100;

    // 传递的数据信息
    protected Bundle myBundle;

    // private static PreferencesHelper s_preferencesHelper;

    // 只用于保存帐户和密码
    // private SharedPreferences s_prefrences;

    /**
     * 状态标识： 正在结束Activity
     */
    protected boolean m_isFinishing;

    /**
     * 状态标识：刷新是否结束
     */
    protected boolean m_refreshFinished;

    /**
     * 刷新时是否压缩网络数据
     */
    protected boolean m_refreshCompressData;

    
	/**
	 * 异步任务类型：火车票刷新类型
	 */
	public final static int JSONTASK_REFRESH_TRAIN = 105;
	
	/**
	 * 客服电话，国内国际机票酒店和火车票各不相同
	 */
	public String m_serviceTelNumber = AppConstants.PHONE_NUMBER;
    // Activity 自有成员：loading框和超时提示框
    // private CustomDialogBuilder loadingDialog;
    // private CustomDialogBuilder timeoutDialog;
	
	
	// 记录上次页面控件点击时间,屏蔽无效点击事件
	protected long mLastOnClickTime = 0;
	protected long mLastOnTouchTime = 0;
    /**
     * 自动刷新时指定的Action类型
     */
    protected String m_refreshAction;

    /**
     * 自动刷新时上传服务器的参数（目前始终为JSON数据格式）
     */
    protected Object m_refreshParams;

    private long mPauseStartTime = -1;

    /**
     * Session超时错误码
     */
    public final static String ERROR_CODE_SESSION_TIMEOUT = "2471";

    /**
     * Session过期提醒,第一次提醒之后不提醒,防止并发调用API多次弹出超时提醒
     */
    private boolean isSessionTimeoutFirstTime = true;

    /**
     * 需要输入验证码(防抓取)
     */
    public final static String ERROR_CODE_NEED_VERIFYCODE = "turtle_1000";

    //消息图标
    protected ImageView messageView ;
    //是否有新消息标志
    protected boolean isHaveNewMessage ;
    //接收消息推送的Receiver
    private Receiver receiver ;
    private int receiverPriority = DEFAULT_RECEIVER_PRIORITY_NO_RECEIVER;

    // public PreferencesHelper getPreferencesHelper() {
    // if (s_preferencesHelper == null) {
    // s_preferencesHelper = new PreferencesHelper(getApplicationContext());
    // InputStream is = null;
    // try {
    // is = getResources().openRawResource(R.raw.preferences);
    // s_preferencesHelper.inflate(is);
    // is.close();
    // } catch (Exception e) {
    // LogWriter.logException(TAG, LogWriter.LOG_LEVEL_NORMAL, e);
    // }
    // is = null;
    // }
    // return s_preferencesHelper;
    // }
    //
    // public SharedPreferences getPrefrences() {
    // if (s_prefrences == null) {
    // s_prefrences = PreferenceManager.getDefaultSharedPreferences(this);
    // }
    // return s_prefrences;
    // }
	/**
	 * 正在运行的异步任务 结束Activity时，会检查当前正在运行的任务并试图去取消这些任务（不一定成功）
	 */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化本地数据
        initLocalData(savedInstanceState);
        // 设置布局文件
        initContentView();
        // 初始化View控件的值,状态和事件监听等
        initViewByLocalData();
        //注册广播
        receiverPriority = getReceiverPriority() ;
        if ( receiverPriority > DEFAULT_RECEIVER_PRIORITY_NO_RECEIVER ) {
            registerReceiver(receiverPriority);
        }

    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: initViews
     * @Description: 初始化页面布局设置
     */
    private void initViewByLocalData() {
        // button back
        View back = findViewById(R.id.common_head_back);
        messageView = (ImageView) findViewById(R.id.common_message);
        if (back != null) {
            back.setOnClickListener(this);
        }
        if (messageView != null) {
            messageView.setOnClickListener(this);
            if (isHomeActivity()) {
                messageView.setImageResource(PrefUtils.getIfHaveNewMessage(this)? R.drawable.icon_home_message_has_new: R.drawable.icon_home_message_common);
            } else {
                messageView.setImageResource(PrefUtils.getIfHaveNewMessage(this)? R.drawable.icon_message_has_new : R.drawable.icon_message_common);
            }
        }

    }

    protected abstract void initContentView();

    private void initLocalData(Bundle savedInstanceState) {
        myBundle = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;

        if (myBundle == null) {
            myBundle = new Bundle();
        }

        // if (s_preferencesHelper == null || s_prefrences == null) {
        // s_preferencesHelper = getPreferencesHelper();
        // s_prefrences = getPrefrences();
        // }

        m_isFinishing = false;
        m_refreshFinished = false;
        m_refreshCompressData = IConfig.COMPRESS_NETWORK_DATA;

        if (IConfig.MANAGE_ACTIVITYSTACK_MANUALLY) {
            Utils.pushActivity(this);
        }

        m_isFinishing = false;
        ElongValidator.setSpecialCharacters(this);

        // loadingDialog = new CustomDialogBuilder(this, CustomDialogBuilder.LOADING_DIALOG_IDS, 0);
        // loadingDialog.setCancelable(false);
        // loadingDialog.setObserver(this);
        // timeoutDialog = new CustomDialogBuilder(this, Utils.DIALOG_IDS, 1);
        // timeoutDialog.setMessage(R.string.network_timeout_prompt);
        // timeoutDialog.setCancelable(false);
        // timeoutDialog.setObserver(this);
        //
        // requestWindowFeature(Window.FEATURE_NO_TITLE);


    }

    public boolean isAlive() {
        return !m_isFinishing;
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_head_back:
                back();
                break;
            case R.id.common_message :
                //TODO
                if (Account.getInstance().isLogin()) {
                    PrefUtils.setIfHaveNewMessage(this,false);
                    startActivity(new Intent(this, MessageListActivity.class));
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra(AppConstants.BUNDLE_KEY_COME_FROM, TAG);
                    startActivityForResult(intent,REQUEST_CODE_LOGIN);
                }
                break ;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_LOGIN :
                    new YouFangLoginManager().YouFangLogin(User.getInstance().getCardNo());
                    break ;
            }
        }
    }

    /**
     * 重写按键处理方法 这里主要实现Back键被按下后的流程（屏蔽系统默认的Back流程，添加数据清理等额外操作）
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {

//        Debug.u(TAG, "BaseActivity onKeyDown()");

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 结束当前Activity并返回上一个Activity<br/>
     * 由于系统的回调方法onDestroy在时间和处理结果上并不能给出保障，这里将清理工作放在finish之前。<br/>
     * 注意：<br/>
     * 1、子类在非必要时不要重写此方法。<br/>
     * 2、子类重写此方法时，必须包含父类back方法的全部逻辑（可以调用super.back）
     */
    public void back() {
        // if (Utils.s_activitiesStack != null && Utils.s_activitiesStack.size() >= 1
        // && Utils.s_activitiesStack.firstElement() != null) {
        // if (!Utils.s_activitiesStack.firstElement().getClass().getName().equals(TabHomeActivity.class.getName())
        // && Utils.s_activitiesStack.size() <= 1) {
        // Intent intent = new Intent(Intent.ACTION_MAIN);
        // intent.addCategory(Intent.CATEGORY_LAUNCHER);
        // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // ComponentName cn = new ComponentName(AppConstants.PACKAGE_NAME, TabHomeActivity.class.getName());
        // intent.setComponent(cn);
        // startActivity(intent);
        // }
        // }
        finish();
        // 添加界面切换效果，注意只有Android的2.0(SdkVersion版本号为5)以后的版本才支持
        int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
        if (version > 4) {
            overridePendingTransition(0, R.anim.push_right_out);
        }

    }

    /**
     * 重写finish()方法， 以前的系统的finish()方法无法将Activity清除Activity栈
     */
    @Override
    public void finish() {
        // preFinish();

        m_isFinishing = true;
        super.finish();
        if (IConfig.MANAGE_ACTIVITYSTACK_MANUALLY) {
            Utils.popActivity();
        }
    }

    /**
     * 回调方法，在Activity结束之前被调用，处理数据清理工作。 注意：
     * 1、每一个子类如果有必须清理的数据，都必须重写此方法清理自己的数据（否则会造成内存泄漏）
     * 2、清理数据的顺序是先清理子类数据，再清理父类数据（即最后调super.preFinish）
     */
    // protected void preFinish() {
    // m_refreshAction = null;
    // m_refreshParams = null;
    // if (loadingDialog != null && loadingDialog.isShowing()) {
    // loadingDialog.dismiss();
    // }
    // if (timeoutDialog != null && timeoutDialog.isShowing()) {
    // timeoutDialog.dismiss();
    // }
    // loadingDialog = null;
    // timeoutDialog = null;
    // }
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
        Utils.hidenputKeyboard(this, getWindow().getDecorView());
        if (receiverPriority > -1 && messageView != null) {
            if (isHomeActivity()) {
                messageView.setImageResource(PrefUtils.getIfHaveNewMessage(this) ? R.drawable.icon_home_message_has_new : R.drawable.icon_home_message_common);
            } else {
                messageView.setImageResource(PrefUtils.getIfHaveNewMessage(this) ? R.drawable.icon_message_has_new : R.drawable.icon_message_common);
            }
        }
    }

    protected void onPause() {
        super.onPause();
//         MobclickAgent.onPause(this);
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getWindow().getDecorView()
                .getWindowToken(), 0);
        // if(updateNotificationManager!=null)updateNotificationManager.cancel(0);
        mPauseStartTime = System.currentTimeMillis();
    }

    /**
     * 设置Activity的Title （显示在顶部导航条中间的文本）
     *
     * @param resId Title文本ID
     */
    public void setHeader(int resId) {
        if (resId == -1) {
            setHeader(null);
        } else {
            setHeader(this.getString(resId));
        }
    }

    /**
     * 设置Activity的Title （显示在顶部导航条中间的文本）
     *
     * @param text Title文本
     */
    protected void setHeader(String text) {
        ((TextView) findViewById(R.id.common_head_title)).setText(text);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            myBundle = savedInstanceState;
        }
        super.onRestoreInstanceState(savedInstanceState);
    }

    public void myStartActivityForResult(Class<? extends Activity> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(this, cls);
        startActivityForResult(intent, requestCode);
        int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
        if (version > 4) {
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        }
    }

    /* 打开新的Activity */
    public void startActivity(Class<? extends Activity> cls, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        intent.setClass(this, cls);
        int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
        if (version > 4) {
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        }
        startActivity(intent);
    }

    /* 打开新的Activity */
    public void startActivity(Intent intent) {
        long currentTimeMillis = System.currentTimeMillis();
        intent.putExtra("mcurrentTimeMillis", currentTimeMillis);
        super.startActivity(intent);
        int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
        if (version > 4) {
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        }
    }

    /* 打开新的半屏Activity */
    public void startActivityFadeIn(Intent intent) {
        super.startActivity(intent);
        int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
        if (version > 4) {
            overridePendingTransition(R.anim.fadein, 0);
        }
    }

    /* 打开新的带有返回值的Activity */
    public void startActivityForResult(Intent intent, int requestCode) {
        long currentTimeMillis = System.currentTimeMillis();
        intent.putExtra("mcurrentTimeMillis", currentTimeMillis);
        super.startActivityForResult(intent, requestCode);
        int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
        if (version > 4) {
            overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        }
    }

    /* 打开新的带有返回值的半屏Activity */
    public void startActivityForResultFadeIn(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
        if (version > 4) {
            overridePendingTransition(R.anim.fadein, 0);
        }

    }

    /**
     * @param response
     * @return boolean
     * @throws
     * @Title: isSessionTimeout
     * @Description: 服务器返回Session超时的场合是否需要登录
     */
    protected boolean isLoginForSessionTimeout(JSONObject response) {
        return (response != null && (ERROR_CODE_SESSION_TIMEOUT.equals(response.getString(JSONConstants.ATTR_ERRORCODE))) && isSessionTimeoutFirstTime);
    }

	
    /**
     * @return void
     * @throws
     * @Title: loginForSessionTimeout
     * @Description: Session超时自动跳转到用户登录页面
     */
    protected void loginForSessionTimeout() {
         isSessionTimeoutFirstTime = false;
         Account.getInstance().logout();
         Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        // intent.putExtra(AppConstants.BUNDLEKEY_REDIRECT, false);
        // startActivityForResult(intent, ACTIVITY_REFRESH_SESSION);
    }

    /**
     * @param @param  response
     * @param @return
     * @return boolean
     * @throws
     * @Title: isNeedVerifyCode
     * @Description: 是否需要验证码(防数据抓取)
     */
    protected boolean isNeedVerifyCode(JSONObject response) {
        // TODO rember to update error code
        return (response != null && (ERROR_CODE_NEED_VERIFYCODE.equals(response.getString(JSONConstants.ATTR_ERRORCODE))));
    }

    /**
     * @param response 验证码图片的URL
     * @return void
     * @throws
     * @Title: showInputVerifyCodeWindow
     * @Description: 输入防抓取验证码
     */
    protected void showInputVerifyCodeWindow(JSONObject response) {
        if (response == null) {
            return;
        }
        // // 验证码图片url
        // String verifyCodeImgurl = response.getString(JSONConstants.ATTR_CHECKURL);
        //
        // PopupWindowUtils.popupNeedVerifyCodeDialog(this, R.layout.verify_code_input_dialog, verifyCodeImgurl);
    }

    /**
     * @param response
     * @return boolean
     * @throws
     * @Title: isNoLoginForSessionTimeout
     * @Description: 静默超时处理
     */
    protected boolean isNoLoginForSessionTimeout(JSONObject response) {
        // TODO rember to update error code
        return (response != null
                && (ERROR_CODE_SESSION_TIMEOUT.equals(response.getString(JSONConstants.ATTR_ERRORCODE)) || "登陆已经过期，请您重新登陆!".equals(response
                .getString(JSONConstants.ATTR_ERRORMESSAGE))) && !isSessionTimeoutFirstTime);
    }
    
    public boolean checkJSONResponse(final Object obj, Object... args) {
		JSONObject response = (JSONObject) obj;
		Log.i("plugin", "--------------- checkjson");
		// Log.e(TAG, "checkJSONResponse: " + response);
		if (response != null) {
			Log.i("plugin", "---------------x1");
			boolean isJsonHelperError = response.getBooleanValue(JSONHelper.KEY_JSONHELPER_ERROR);
			if (isJsonHelperError) {
				int errorCode = response.getIntValue(JSONHelper.KEY_JSONHELPER_ERRORCODE);
				// Log.e(TAG, "JsonHelper Error: " + errorCode);
				switch (errorCode) {
				case JSONHelper.EVENT_NETWORK_ERROR:
					DialogUtils.showInfo(this, -1, R.string.network_error);
					break;

				case JSONHelper.EVENT_SERVER_ERROR:
					DialogUtils.showInfo(this, -1, R.string.server_error);
					break;

				case JSONHelper.EVENT_JSON_ERROR:
					DialogUtils.showInfo(this, -1, R.string.unknown_error);
					break;
				}
				return false;
			}
			boolean succeed = !response.getBooleanValue(JSONConstants.ATTR_ISERROR);
			if (!succeed) {
				if (isLoginForSessionTimeout(response)) {
					loginForSessionTimeout();
					return succeed;
				} else if (isNoLoginForSessionTimeout(response)) {
					return succeed;
				} else if (isNeedVerifyCode(response)) {
					showInputVerifyCodeWindow(response);
					return succeed;
				}
				String errorMessage = response.getString(JSONConstants.ATTR_ERRORMESSAGE);
				if (Utils.isEmptyString(errorMessage)) {
					errorMessage = this.getString(R.string.unknown_error);
				}
				DialogUtils.showNoCancelInfo(this, null, errorMessage, null);
			}
			return succeed;
		} else {
			DialogUtils.showInfo(this.getBaseContext(), -1, R.string.network_error);
			return false;
		}
	}
	/**
	 * 
	 * @Title: isWindowLocked
	 * @Description: 屏幕是否被锁定(不可点击)
	 * @param @return
	 * @return boolean
	 * @throws
	 */
	public boolean isWindowLocked() {
		long current = SystemClock.elapsedRealtime();
		Log.d("time", "current - mLastOnClickTime: " + (current - mLastOnClickTime) + ",current: " + current
				+ ",mLastOnClickTime: " + mLastOnClickTime);
		if (current - mLastOnClickTime > IConfig.SCREEN_RELEASE_TIME) {
			mLastOnClickTime = current;
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 淡入淡出效果的Activity， 使用此back()方法
	 */
	public void backFadeOut() {
		finish();
		// 添加界面切换效果，注意只有Android的2.0(SdkVersion版本号为5)以后的版本才支持
		int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);
		if (version > 4) {
			overridePendingTransition(0, R.anim.fadeout);
		}
	}

    private class Receiver extends BroadcastReceiver {

        private final Handler handler ;

        public Receiver(Handler handler) {
            this.handler = handler ;
        }

        @Override
        public void onReceive(Context context, final Intent intent) {
//            String data = bundle.getString("payload");
            String action = intent.getAction() ;
            Log.i(TAG, "onReceive  " + action);
            if (action.equals(PushReceiver.ACTION_GET_CID_SUCCESS)) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        PluginBaseActivity.this.onReceive(intent);
                    }
                });
            } else {
//                ImPushPayloadContent content = (ImPushPayloadContent) intent.getSerializableExtra(AppConstants.KEY_PAYLOAD);
                if (messageView != null) {
                    if (isHomeActivity()) {
                        messageView.setImageResource(R.drawable.icon_home_message_has_new);
                    } else {
                        messageView.setImageResource(R.drawable.icon_message_has_new);
                    }
                }
                if (receiverPriority > AppConstants.RECEIVER_PRIORITY_HOME) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            PluginBaseActivity.this.onReceive(intent);
                        }
                    });
                    abortBroadcast();
                } else {
                    PrefUtils.setIfHaveNewMessage(context, true);
                }
            }
        }
    }

    /**
     * 收到推送通知后的处理，在activity主线程中进行
     * @param intent
     */
    protected void onReceive(final Intent intent) {

    }

    /**
     * 1、设置Receiver的优先级，默认-1表示此Activity不注册广播
     * 2、需要注册对消息时间广播相应的Activity需要重写此方法
     * @return 数字越大优先级越高 (-1000~1000)，返回值以常量的形式定义在{@link AppConstants}中
     */
    protected int getReceiverPriority() {
        return DEFAULT_RECEIVER_PRIORITY_NO_RECEIVER ;
    }

    protected boolean isHomeActivity() {
        return false ;
    }
    private void registerReceiver(int priority) {
        receiver = new Receiver(new Handler()) ;
        IntentFilter filter = new IntentFilter();
        filter.addAction(PushReceiver.ACTION_GET_MESSAGE);
        filter.addAction(PushReceiver.ACTION_GET_CID_SUCCESS);
        filter.setPriority(priority);
        this.registerReceiver(receiver, filter) ;
    }

    @Override
    protected void onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
        super.onDestroy();
    }
}
